﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SisocanaFronEnd.Models;
using System.Web.Routing;
using Sisocana.Core.Models;
using System.IO;

namespace SisocanaFronEnd.Controllers
{
    public class SiteController : Controller
    {
        ISiteProvider _siteProvider;

        public SiteController()
        {
            _siteProvider = new SiteProvider();
        }

        public SiteController(ISiteProvider siteProvider)
        {
            _siteProvider = siteProvider;
        }

        public SiteModel Site
        {
            get { return _siteProvider.GetCurrentSite(); }
        }

        private string GetSubdomain(RequestContext rc)
        {
            string host = rc.HttpContext.Request.Headers["Host"].Split(':')[0];
            string subdomain = host;
            int lugar = host.IndexOf(".");
            if (lugar > 0)
            {
                subdomain = host.Substring(0, lugar);
                if (subdomain.Equals("www"))
                {
                    host = host.Substring(lugar + 1);
                    lugar = host.IndexOf(".");
                    subdomain = host.Substring(0, lugar);
                }
            }
            return subdomain;
        }

        protected override void Initialize(RequestContext requestContext)
        {   
            _siteProvider.Initialise(GetSubdomain(requestContext));

            // Cargo los datos para mostrar twitters y mapa
            SiteModel sit = _siteProvider.GetCurrentSite();
            if (sit.estado == "O")
            {
                ViewBag.feeds = Site.sources;
                ViewData["idSitio"] = Site.id.ToString();
                ViewData["userTweet"] = Site.tweetuser.Trim();
                ViewData["userFace"] = Site.faceuser.Trim();
                ViewData["tweetSearch"] = Site.tweetsearch.Trim();
                ViewData["cantTweet"] = Site.tweetCant;

                // Dimensiones y colores de los tweets                 
                ViewData["theigth"] = Site.theigth;
                ViewData["twidth"] = Site.theigth;
                ViewData["btColor"] = Site.btColor.Trim();
                ViewData["tColor"] = Site.tColor.Trim();
                ViewData["bsColor"] = Site.bsColor.Trim();
                ViewData["sColor"] = Site.sColor.Trim();

                ViewData["fechaFormat"] = String.Format("{0:dd/MM/yyyy}", Site.fecha);

                ViewData["affectedLocations"] = _siteProvider.Services.getAreasAfectadas(Site.id);
            }
            base.Initialize(requestContext);
        }

        // La lógica estaba sólo en Home, por lo que no contemplaba el caso de que el usuario acceda directamente a otra URL
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            switch (Site.estado)
            {
                case "M":
                    filterContext.Result = RedirectToAction("Mantenimiento",
                                            new RouteValueDictionary(new { controller = "Error", action = "Mantenimiento", id = Site.tituloWeb }));
                    break;
                case "I":
                    filterContext.Result = RedirectToAction("Inactiva",
                                            new RouteValueDictionary(new { controller = "Error", action = "Inactiva", id = Site.tituloWeb }));
                    break;
                case "O":
                    ViewBag.Site = Site;
                    base.OnActionExecuting(filterContext);
                    break;
                default:
                    filterContext.Result = RedirectToAction("NoSite",
                                            new RouteValueDictionary(new { controller = "Error", action = "NoSite", id = Site.subdominio }));
                    break;
            }
        }
        
        protected string RenderPartialViewToString(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = ControllerContext.RouteData.GetRequiredString("action");

            ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);

                return sw.GetStringBuilder().ToString();
            }
        }
    }
}
